<%@page import="java.util.stream.Collectors"%>
<%@page import="common.Helper"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ page import="table.*"%>
<%@ page import="java.util.*"%>
<%@ page import="common.Helper"%>

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>同行评价系统管理员主页</title>
<link href="css/twoColLiqLt.css" rel="stylesheet" type="text/css">
<link href="css/tableStyles.css" rel="stylesheet" type="text/css">
<link href="css/frameStyles.css" rel="stylesheet" type="text/css">
<!--[if lte IE 7]>
<style>
.content { margin-right: -1px; } /* 此 1px 负边距可以放置在此布局中的任何列中，且具有相同的校正效果。 */
ul.nav a { zoom: 1; }  /* 缩放属性将为 IE 提供其需要的 hasLayout 触发器，用于校正链接之间的额外空白 */
</style>
<![endif]-->
</head>
<%
	// 管理员登录有效性验证段
	User user = (User) session.getAttribute("user");
	if (user == null || !user.getGroup().equals("admin")) {
		request.getRequestDispatcher("index.jsp").forward(request, response);
		return;
	}

	// 获取参数指定的评价活动，保存在变量selectedEe中
	int eeid = 0;
	try {
		eeid = Integer.valueOf(request.getParameter("eeid"));
	} catch (Exception e) {
	}

	EvalHandle ehandle = new EvalHandle();
	EvaluationEvent selectedEe = ehandle.getEeById(eeid);
	if (selectedEe == null) {
		out.println("<script>alert('There no event id = " + eeid + "');window.history.back(-1);</script>");
		return;
	}
%>
<script>
function isDelete(teamid){
	if(confirm("确认删除？")){
		delete_team(teamid);
	}
	
}
function delete_team(teamid){
	if (window.XMLHttpRequest) {
		xmlhttp = new XMLHttpRequest();
	} else {
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	//设置传送方式,地址,以及同步还是异步
	xmlhttp.open("GET", "DeleteteamofEe?eeid=<%=eeid%>&teamid="+escape(teamid), true);
	xmlhttp.onreadystatechange = callback;//状态改变的时候执行这个函数,用来判断是否请求完毕
	xmlhttp.send();//请求服务器	
}

function callback(){
	if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
		var result = xmlhttp.responseXML.getElementsByTagName('result')[0].textContent;
		if (result === "OK") {
			alert("删除小组成功")
			location.reload(); // 成功则直接刷新页面（这时会在页面中显示新的活动）
		} else {
			alert("删除小组失败！");
		}
	}
}

function update_btn(){
	var btn_start = document.getElementById('btn_start');
	var btn_stop = document.getElementById('btn_stop');
	var lbl_stat = document.getElementById('ee_stat');
	var stat = lbl_stat.innerText;
	if(stat === 'init' || stat === 'pause'){
		btn_start.disabled = false;
		btn_start.value = '开启';
	} else if(stat === 'available') {
		btn_start.disabled = false;
		btn_start.value = '暂时关闭';
	} else {
		btn_start.disabled = true;
		btn_start.value = '开启';
	}
	if(stat === 'stop'){
		btn_stop.value = '恢复初始态';
	} else {
		btn_stop.value = '结束';
	}
}

function change_stat1(){
	
	var stime = document.getElementById('start_time').valueAsNumber;
	var etime = document.getElementById('end_time').valueAsNumber;
	if(isNaN(stime) || isNaN(etime)) {
		alert('请先设置开始和结束时间！');
		return;
	}
	if(!checkTimeValid()) return;
	
	var btn_start = document.getElementById('btn_start');
	var func_str = btn_start.value;
	var curr_stat = document.getElementById('ee_stat').innerText;
	
	var stat = 'nope';
	
	if(func_str === '开启'){
		if(curr_stat === 'init'){
			stat = 'prepare';
		} else if(curr_stat === 'pause') {
			stat = 'available';
		}
	} else if(func_str === '暂时关闭') {
		if(curr_stat === 'available'){
			stat = 'pause';
		}
	}
	
	if (window.XMLHttpRequest) xmlhttp = new XMLHttpRequest();
	else xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	
	xmlhttp.open("GET", "ChangeStatus?eeid=<%= eeid %>&status=" + escape(stat), true);
	xmlhttp.onreadystatechange = callback2;
	xmlhttp.send();
}

function change_stat2(){
	
	var btn_stop = document.getElementById('btn_stop');
	var func_str = btn_stop.value;
	var curr_stat = document.getElementById('ee_stat').innerText;
	
	var stat = 'nope';
	
	if(func_str === '结束'){
		stat = 'stop';
	} else if(func_str === '恢复初始态') {
		if(curr_stat === 'stop') stat = 'init';
	}
	
	if (window.XMLHttpRequest) xmlhttp = new XMLHttpRequest();
	else xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	
	xmlhttp.open("GET", "ChangeStatus?eeid=<%= eeid %>&status=" + escape(stat), true);
	xmlhttp.onreadystatechange = callback2;
	xmlhttp.send();
}

function callback2(){
	if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
		var result = xmlhttp.responseXML.getElementsByTagName('result')[0].textContent;
		if (result === "OK") {
			var stat = xmlhttp.responseXML.getElementsByTagName('status')[0].textContent;
			document.getElementById('ee_stat').innerText = stat;
			alert("切换状态成功！");
			update_btn();
		} else {
			alert("切换状态失败！");
		}
	}
}

function checkTimeValid(){
	var stime = document.getElementById('start_time').valueAsNumber;
	var etime = document.getElementById('end_time').valueAsNumber;
	if(isNaN(stime) || isNaN(etime))
		return true;
	if(stime < etime)
		return true;
	alert('开始时间必须小于结束时间！');
	return false;
}

</script>

<script>
function initStyle(){
	var ele = document.getElementById("login_text");
	ele.innerText = "登录信息：<%= user.getName() %> (<%= user.getId() %>)";
	update_btn();
}
</script>


<body onload="initStyle();">

<div class="container">

	<%@ include file="admin_menu.html"%>

	<div class="content">

		<div id="frame">
			<h3>评价活动ID：<%= selectedEe.getId() %></h3>
			<div id="frame_header" style="display:table;">
			<div style="display:table-row;">
			<div id="left_main" style="display:table-cell;width:460px;">
				<form action="ChangeEEName" method="post">
			评价活动名称:
			    <input type="text" name="EeName" value=<%= selectedEe.getName()%>>
				<input type="submit" name="submit_eename" value="修改">
					<input type="hidden" name="eeid" value="<%=eeid%>">
					<input type="button" name="show_detail" value="查看详细评价记录" onclick="window.open('admin_eval_specific.jsp?eeid=<%= eeid %>');">
				</form> 
				评价活动状态：<label id="ee_stat"><%= selectedEe.getStatus() %></label>
				<input type="button" name="btn_start" id="btn_start" value="开启" onclick="change_stat1();"> 
				<input type="button" name="btn_stop" id="btn_stop" value="结束" onclick="change_stat2();">
				<form action="ChangeStarttime" method="post">
					设置评价活动开始时间：
					<%
					String stime = selectedEe.getStartTime();
					if (stime == null || "".equals(stime) || "null".equalsIgnoreCase(stime)) {
						out.println("<input id=\"start_time\" type=\"datetime-local\" name=\"start_time\" value=\"\">");
					} else {
						String htmltime = Helper.dateToHTMLTime(Helper.DBTimeToDate(stime));
						out.println("<input id=\"start_time\" type=\"datetime-local\" name=\"start_time\" value=\"" + htmltime + "\">");
					}
					%>
					<input type="submit" name="submit_starttime" value="修改" onclick="return checkTimeValid();">
					<input type="hidden" name="eeid" value="<%=eeid%>">
				</form>
				<form action="ChangeEndtime" method="post">
					设置评价活动结束时间：
					<%
					String etime = selectedEe.getEndTime();
					if (etime == null || "".equals(etime) || "null".equalsIgnoreCase(etime)) {
						out.println("<input id=\"end_time\" type=\"datetime-local\" name=\"end_time\" value=\"\">");
					} else {
						String htmltime = Helper.dateToHTMLTime(Helper.DBTimeToDate(etime));
						out.println("<input id=\"end_time\" type=\"datetime-local\" name=\"end_time\" value=\"" + htmltime + "\">");
					}
					%>
					<input type="submit" name="submit_endtime" value="修改" onclick="return checkTimeValid();">
					<input type="hidden" name="eeid" value="<%=eeid%>">
				</form>
				<form action="ChangeInfo" method="post">
				设置评价活动简介：<br>
					<textarea name="team_info" rows="9" cols="58"><%=selectedEe.getInfo()%></textarea>
					<input type="submit" name="submit_teaminfo" value="修改">
					<input type="hidden" name="eeid" value="<%=eeid%>">
				</form>
			<!-- end left_main --></div>
			<div id="right_info" style="display:table-cell;">
			<p style="font-size:85%;">
			<strong style="font-size:120%;">状态说明</strong><br>
			<strong>init（初始态）：</strong>活动刚建立时的默认状态，点击“开启”离开该状态。<br>
			<strong>prepare（准备态）：</strong>开始时间之前的这段时间为准备阶段，小组成员可以在该时期设置本次活动中自己小组的信息。<br>
			<strong>available（可评价态）：</strong>开始时间到结束时间之间为可评价态，小组成员可以进入评价活动评价。<br>
			<strong>pause（暂停态）：</strong>处于可评价态时管理员可以按暂停按钮，暂时关闭评价入口。<br>
			<strong>stop（结束态）：</strong>当系统时间到达结束时间时，会自动进入结束态。结束态时，小组成员可以查看本次评价结果。<br>
			</p>
			<!-- end right_info --></div>
			<!-- end row --></div>
			<!-- end frame_header --></div>

			<div id="frame_content">
				<!-- 显示学生列表内容 -->
				<form action="AddTeamOfEe" method="post">
					添加参与该评价活动的小组：<input type="text" name="add_team" value="" placeholder="输入小组id" list="team_list">
					<input type="submit" name="btu_add_team" value="添加小组">
					<input type="hidden" name="eeid" value="<%=eeid%>">
				</form>
				<table class="list" width="100%" border="1">
					<thead>
						<th width="10%">小组ID</th>
						<th width="18%">小组名称</th>
						<th width="12%">实验名</th>
						<th width="10%">小组成员数</th>
						<th width="10%">已评价人数</th>
						<th width="10%">被评分次数</th>
						<th width="15%">目前平均得分</th>
						<th width="15%">移除该组资格</th>
					</thead>
					<tr>

						<%
							// 输出参与评论的小组
							TeamHandle thandle = new TeamHandle();
							UserHandle uhandle = new UserHandle();
							List<Attendant> list = ehandle.getAttendantsFromEe(selectedEe.getId());
							for (Attendant a : list) {

								List<User> teamMembers = thandle.getUsersFromTeam(a.getTeamid());
								List<String> teamMemberIDs = teamMembers.stream().map(u->u.getId()).collect(Collectors.toList());
								List<Evaluation> evalsToTeam = ehandle.getEvalsForTeamInEe(a.getTeamid(), eeid);
								List<Evaluation> evalsFromTeam = ehandle.getAllEvalsFromEe(eeid);
								DoubleSummaryStatistics dss = evalsToTeam.stream().filter(eval->eval.getScore()!=0).mapToDouble(Evaluation::getScore).summaryStatistics();
								
								// 小组ID
								String tid = "" + a.getTeamid();
								// 小组名称
								String tname = a.getTeamName();
								// 实验名
								String isSetInfo = a.getEname() == null || a.getEname().isEmpty() ? "未设置" : a.getEname();
								// 小组成员数
								String numOfTeam = "" + teamMembers.size();
								// 已评价人数
								String numOfPeopleWhoEvaled = "" + evalsFromTeam.stream().filter(eval->eval.getScore()!=0).filter(eval->teamMemberIDs.contains(eval.getUserid())).collect(Collectors.groupingBy(Evaluation::getUserid, Collectors.toSet())).size();
								// 被评分次数
								String numOfBeingEval = "" + dss.getCount();
								// 目前平均分
								String aveScore = dss.getCount() == 0 ? "未被评价" : String.format("%.2f", dss.getAverage());
								// 移除该组资格
								String deleteTeam = "<a href=\"#\" onclick=\"isDelete(" + a.getTeamid() + "); return false;\">删除</a>";
								String line = String.format("<td>%s</td><td>%s</td><td" + ( a.getEname()==null ? " style=\"color:red\"" : "") + 
															">%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td>",
															tid, tname, isSetInfo, numOfTeam, numOfPeopleWhoEvaled, numOfBeingEval, aveScore, deleteTeam);
								out.println("<tr>" + line + "</tr>");
							}
						%>

					
				</table>

				<datalist id="team_list">
					<%
						List<Team> tlist = thandle.getAllTeams();
						for (Team t : tlist) {
							out.println(String.format("<option label=\"%s\" value=\"%d\" />", t.getName(), t.getId()));
						}
					%>
				</datalist>
			</div>
			<input type="button" name="back" value="返回" onclick="window.location.href='admin_ee_manage_main.jsp'">
		</div>
	<!-- end .content --> </div>
	<%@ include file="footer.html" %>
	<!-- end .container --> </div>
</body>
</html>
